import { constantRoutes } from '@/router'
import Layout from '@/layout'
import store from '@/store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.path,
      component: item.component === 'Layout' ? Layout : (resolve) => require([`@/views/${item.component}`], resolve),
      hidden: item.hidden,
      children: [],
      name: item.meta.title,
      meta: {
        title: item.meta.title,
        icon: item.meta.icon,
        id: item.id,
        roles: ['admin']
      }
    }
    if (item.children) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}

/**
 * 动态路由改造： 将 asyncRoutes 改造成从后台中获取，并满足格式要求
 * @type {{generateRoutes({commit: *}, *=): Promise<unknown>}}
 */
const actions = {
  async generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const myAsyncRoutes = [
        // 404 page must be placed at the end !!!
        { path: '*', redirect: '/404', hidden: true }
      ]
      // 从后台请求的路由信息
      const myLocalRoutes = []
      store.dispatch('user/getPermissionByToKen').then((res) => {
        Object.assign(myLocalRoutes, res.menu)
        // 构建可渲染的routes格式
        generaMenu(myAsyncRoutes, myLocalRoutes)
        // 存放最终可以访问的路由信息
        let accessedRoutes = myAsyncRoutes || []
        // // 判断当前角色列表中是否包含 admin
        // if (roles.includes('admin')) {
        //   // 所有路由都可以访问
        //   accessedRoutes = myAsyncRoutes || []
        // } else {
        //   // 根据角色过滤不能访问的路由
        //   accessedRoutes = filterAsyncRoutes(myAsyncRoutes, roles)
        // }
        commit('SET_ROUTES', accessedRoutes)
        // 返回路由
        resolve(accessedRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
